/*
 * Created by SharpDevelop.
 * User: MyWife
 * Date: 6/5/2010
 * Time: 10:10 AM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
using popLib;
using Microsoft.Win32;
using System.IO;


namespace FileAssociateManager
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public partial class MainForm : Form
	{
		DataSet data = DataLib.initDataSet(" Types[ #Type, Icon, CommmandSet, DefaultShell ] \r\n Commands[ Type, Shell, Command ] ");
		string filesave = FileLib.getFullPath("data.dat");
		DataTable currentShellData = DataLib.initDataTable( "Command[ Shell, Command, DefaultShell ]" );
		int currentTypeIndex = -1;
		public MainForm()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
//			data.Tables["Types"].Rows.Add(    new object[]{ "AAA", "shell32.dll,210", "FT-AAA", "open" } );
//			data.Tables["Commands"].Rows.Add( new object[]{ "AAA", "open", "\"notepad.exe\" \"%1\"" } );
//			data.Tables["Commands"].Rows.Add( new object[]{ "AAA", "view", "\"notepad.exe\" \"%1\"" } );			
//			ApplyFileType( "aaa" );
			
			
			
			detail_dgv_shellList.DataSource = currentShellData;
			
			txt_search.TextChanged += delegate { 
				lbx_type.SelectedIndex = lbx_type.FindString( txt_search.Text );				
			};
			
			btn_newtype.Click += delegate { 
				detail_lbl_icon.Text = detail_txt_typeName.Text = detail_txt_iconfile.Text = "";
				currentShellData.Clear();
				//detail_txt_typeName.ReadOnly = false;
				currentTypeIndex = -1;
			};
			
			EventHandler typeIndexChange = delegate(object sender, EventArgs e) { 
				if( lbx_type.SelectedIndex == -1 ) return;
				currentTypeIndex = lbx_type.SelectedIndex;
				
				detail_txt_typeName.Text = data.Tables[0].Rows[currentTypeIndex]["Type"].ToString();
				detail_txt_iconfile.Text = data.Tables[0].Rows[currentTypeIndex]["Icon"].ToString();
				detail_txt_commandSetName.Text = data.Tables[0].Rows[currentTypeIndex]["CommmandSet"].ToString();
				string defaultShell = data.Tables[0].Rows[currentTypeIndex]["DefaultShell"].ToString();
				
				currentShellData.Clear();
				DataRow[] rows = data.Tables[1].Select( "Type = '"+detail_txt_typeName.Text+"'" );
				foreach( DataRow row in rows ){
					currentShellData.Rows.Add( new object[]{ 
					                          row["Shell"].ToString(),
					                          row["Command"].ToString(),
					                          defaultShell == row["Shell"].ToString()
					                          } );
				}
			};
			
			lbx_type.SelectedIndexChanged += typeIndexChange;
			
			detail_btn_save.Click += delegate { 
				if( currentTypeIndex == -1 ){					
					DataRow row = data.Tables[0].Rows.Find( detail_txt_typeName.Text );
					
					if( row != null ) {
						FormLib.alert("This type is already add to list");						
						detail_txt_typeName.SelectAll();
						detail_txt_typeName.Focus();
						return;
					}
					
					lbx_type.SelectedIndexChanged -= typeIndexChange;
					string defaultShell = "";
					foreach( DataRow eachrow in currentShellData.Rows ){
						if( eachrow["DefaultShell"] != null &&  eachrow["DefaultShell"].ToString() == "true" ){
							defaultShell = eachrow["Shell"].ToString();							
						}
						data.Tables[1].Rows.Add( new string[]{
						                        	detail_txt_typeName.Text.Trim().ToUpper(),
						                        	eachrow["Shell"].ToString(),
						                        	eachrow["Command"].ToString()
						                        } );
					}
					
					detail_txt_commandSetName.Text = "FT-"+detail_txt_typeName.Text.Trim().ToUpper();
					
					data.Tables[0].Rows.Add( new string[]{ 
					                        	detail_txt_typeName.Text.Trim().ToUpper(),
					                        	detail_txt_iconfile.Text,
					                        	detail_txt_commandSetName.Text,
					                        	defaultShell
					                        } );
										
					SaveData();
					
					lbx_type.SelectedIndexChanged += typeIndexChange;
					
				}else{
					DataRow row = data.Tables[0].Rows[currentTypeIndex];
					if( row == null ){
						FormLib.alert("Cannot find your file type to update");
						return;
					}
					
					lbx_type.SelectedIndexChanged -= typeIndexChange;
					
					DataRow[] currentTypeRows = data.Tables[1].Select( "Type = '" + row["Type"].ToString() + "'" );
					foreach( DataRow delRow in currentTypeRows )
						data.Tables[1].Rows.Remove( delRow );
					
					detail_txt_commandSetName.Text = "FT-"+detail_txt_typeName.Text.Trim().ToUpper();
					
					row["Type"] = detail_txt_typeName.Text;
					row["Icon"] = detail_txt_iconfile.Text;
					row["CommmandSet"] = detail_txt_commandSetName.Text;
					
					foreach( DataRow addRow in currentShellData.Rows )
						data.Tables[1].Rows.Add( new string[]{
						                        	detail_txt_typeName.Text,
						                        	addRow["Shell"].ToString(),
						                        	addRow["Command"].ToString()
						                        } );
					
					SaveData();
					
					lbx_type.SelectedIndexChanged += typeIndexChange;
				}
			};
			
			btn_applyAll.Click += delegate { 
				Global.Instance().ApplyFileType();
				FormLib.alert("Apply All file types done.");
			};
			
			lbx_type.KeyUp += delegate(object sender, KeyEventArgs e) { 
				if( e.KeyCode == Keys.Delete && lbx_type.SelectedIndex >= 0 && FormLib.confirm("Are you sure, you want to remove this file type ?") ){
					DataRow selectedRow = data.Tables[0].Rows[ lbx_type.SelectedIndex ];
					
					string Type = selectedRow["Type"].ToString();
					
					DataRow[] currentTypeRows = data.Tables[1].Select( "Type = '" + selectedRow["Type"].ToString() + "'" );
					foreach( DataRow delRow in currentTypeRows )
						data.Tables[1].Rows.Remove( delRow );
					
					data.Tables[0].Rows.Remove( selectedRow );
					
					Global.Instance().RemoveFileType( Type );
					
					SaveData();
				}					
			};
			
			detail_btn_browse.Click += delegate { 
				ReturnSet rs = FormLib.openFile( "All files(*.png,*.exe,*.ico)|*.png;*.exe;*.ico" );
				if( rs.Success ){
					detail_txt_iconfile.Text = rs.Result.ToString();
				}
			};
			
			LoadData();
			
		}
		
		#region Handle dataset functions
		void LoadData(){
			if( File.Exists(filesave) )
				data.ReadXml( filesave );
			
			lbx_type.DataSource    = data.Tables[0];
			lbx_type.DisplayMember = "Type";
			lbx_type.ValueMember   = "Type";
		}
		
		void SaveData(){
			data.WriteXml( filesave );
		}
		#endregion
		
		
		
	}
}
